package com.wego.controller.admin;


import com.wego.anno.Log;
import com.wego.bean.PageBean;
import com.wego.bean.ResultBean;
import com.wego.converter.UserConverter;
import com.wego.domain.dto.UserDTO;
import com.wego.domain.entity.User;
import com.wego.domain.excel.UserExcel;
import com.wego.domain.query.UserQuery;
import com.wego.domain.vo.UserVO;
import com.wego.ex.GlobalException;
import com.wego.service.UserService;
import com.wego.utils.Md5Util;
import com.wego.utils.StringUtil;
import com.wego.utils.excel.EasyExcelListener;
import com.wego.utils.excel.EasyExcelUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/admin/user")
public class AdminUserController {
    @Resource
    private UserService userService;
    @Resource
    private UserConverter userConverter;
    @Log
    @PostMapping
    public ResultBean<Void> insert(@RequestBody UserDTO userDTO) {
        final User user = userConverter.dto2entity(userDTO);
        if (userService.isAccountExist(user.getAccount())) {
            return ResultBean.error("账号已存在", null);
        }
        user.setSalt(StringUtil.genStr(28));
        user.setPassword(Md5Util.encode(user.getPassword(), user.getSalt()));
        user.setUpdateTime(LocalDateTime.now());
        if (user.getNickname() == null || user.getNickname().isEmpty()) {
            user.setNickname(user.getAccount());
        }
        if (user.getGender() == null) {
            user.setGender(0);
        }
        if (user.getState() == null) {
            user.setState(0);
        }
        user.setCreateTime(LocalDateTime.now());
        userService.insert(user);
        return ResultBean.success("添加成功!", null);
    }

    @GetMapping("/page")
    public ResultBean<PageBean<UserVO>> page(UserQuery userQuery) {
        final PageBean<User> userPageBean = userService.getPage(userQuery);
        final PageBean<UserVO> userVOPageBean = userConverter.entityPageBean2voPageBean(userPageBean);
        return ResultBean.success(userVOPageBean);
    }

    @GetMapping("/all")
    public ResultBean<List<UserVO>> all() {
        log.info("获取所有用户列表");
        final List<UserVO> list = userService.getList();
        return ResultBean.success(list);
    }
    @GetMapping("/account/{account}")
    public ResultBean<UserVO> getDetails(@PathVariable String account) {
        final User user = userService.getByAccount(account);
        final UserVO userVO = userConverter.user2userVO(user);
        if(user == null)
            return ResultBean.error("用户不存在", null);
        return ResultBean.success(userVO);
    }
    @GetMapping("/{id}")
    public ResultBean<UserVO> getDetails(@PathVariable Integer id) {
        final User user = userService.getById(id);
        if(user == null)
            return ResultBean.error("用户不存在", null);
        final UserVO userVO = userConverter.user2userVO(user);
        return ResultBean.success(userVO);
    }
    @Log
    @PutMapping
    public ResultBean<Void> update(@RequestBody UserDTO userDTO) {
        // 检查用户是否存在
        User existingUser = userService.getById(userDTO.getId());
        if (existingUser == null) {
            return ResultBean.error("用户不存在", null);
        }
        // 转换DTO为实体
        final User user = userConverter.dto2entity(userDTO);
        // 保留原密码和盐值，如果DTO中没有提供新密码
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword(existingUser.getPassword());
            user.setSalt(existingUser.getSalt());
        } else {
            // 如果提供了新密码，则重新生成盐值并加密
            String salt = StringUtil.genStr(28);
            user.setSalt(salt);
            user.setPassword(Md5Util.encode(user.getPassword(), salt));
        }
        // 设置更新时间
        user.setUpdateTime(LocalDateTime.now());
        // 执行更新操作
        int result = userService.update(user);
        if (result > 0) {
            return ResultBean.success("修改成功!", null);
        } else {
            return ResultBean.error("修改失败", null);
        }
    }
    @Log
    @DeleteMapping
    public ResultBean<Void> batchDelete(@RequestParam List<Integer> ids) {
        userService.deleteByIds(ids);
        return ResultBean.success("批量删除成功!", null);
    }
    @Log
    @PostMapping("/export")
    public void exportData(HttpServletResponse response, @RequestBody UserQuery userQuery) {
        final PageBean<User> pageBean = userService.getPage(userQuery);

        final List<UserExcel> list = userConverter.entityList2excelList(pageBean.getRecords());
        try {
            EasyExcelUtil.writeWithSheetsWeb(response, "user列表")
                    .writeModel(UserExcel.class, list, "user")
                    .finish();
        } catch (IOException e) {
            throw new GlobalException("用户信息导出失败！");
        }
    }
    @Log
    @PostMapping("/import")
    public ResultBean<Void> importData(@RequestPart(value = "file", required = true) MultipartFile file) {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            return ResultBean.error("请选择要导入的文件", null);
        }

        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !originalFilename.toLowerCase().endsWith(".xlsx") && !originalFilename.toLowerCase().endsWith(".xls")) {
            return ResultBean.error("请上传Excel格式的文件", null);
        }

        try {
            try (InputStream is = file.getInputStream()) {
                final EasyExcelListener<UserExcel> listener = new EasyExcelListener<UserExcel>() {
                    @Override
                    protected void exec(List<UserExcel> list) {
                        try {
                            // 数据转换和批量插入
                            final List<User> userList = userConverter.excelList2entityList(list);
                            userService.batchInsert(userList);

                            // 记录导入任务完成日志
                            log.info("Excel导入完成，批次数据量：{}", userList.size());
                        } catch (Exception e) {
                            // 处理数据导入异常
                            log.error("Excel数据处理异常", e);
                            // 可以添加任务失败的处理逻辑，如记录失败日志等
                        }
                    }
                };
                EasyExcelUtil.asyncReadModel(is, listener, UserExcel.class);
            }

            return ResultBean.success("数据导入任务已提交，请等待处理完成", null);
        } catch (Exception e) {
            log.error("Excel文件读取异常", e);
            return ResultBean.error("文件解析失败：" + e.getMessage(), null);
        }
    }

}